//
//  PersonListController.m
//  CoreData
//
//  Created by ZRAR on 16/1/15.
//  Copyright © 2016年 ZRAR. All rights reserved.
//

#import "PersonListController.h"
#import "PersonViewModel.h"
#import "NewPersonController.h"

@interface PersonListController ()


@end

@implementation PersonListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = self.editButtonItem;
   
    @weakify(self);
    [self.viewModel.updatedContentSingal subscribeNext:^(id x) {
       
        @strongify(self);
        [self.tableView reloadData];
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    
    return [self.viewModel numberOfSections];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return [self.viewModel numberOfItemsInSections:section];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return [self.viewModel titleForSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];
    
    cell.textLabel.text = [self.viewModel titleAtIndexPath:indexPath];
    cell.detailTextLabel.text = [self.viewModel subtitleAtIndexPath:indexPath];
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [self.viewModel deleteObjectAtIndexPath:indexPath];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NewPersonController *newCol = [self.storyboard instantiateViewControllerWithIdentifier:@"NewPersonController"];
    newCol.viewModel = [self.viewModel editViewModelForIndexPath:indexPath];
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:newCol];
    [self presentViewController:navigationController animated:YES completion:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    if ([[segue identifier] isEqualToString:@"editPerson"]) {
        
        NewPersonController *controller = (NewPersonController *)[segue.destinationViewController topViewController];
        
        controller.viewModel = [self.viewModel editViewModelForNewPerson];
    }
    
}


@end
